var numtip = "请输入数字";
var areacodenulltip = "请输入区号";
var extnulltip = "请输入分机";
var reg = new RegExp("^[0-9]*$");

function keyup() {
  //座机验证
  $("#areacodeErr").show();
  if ($("#areacode").val()) {
    if (!reg.test($("#areacode").val())) {
      $("#areacodeErr").html(numtip)
      $("#areacodeErr").show();
    }
    else {
      $("#areacodeErr").hide();
    }

  }

}


function extkeyup() {
  var reg = new RegExp("^[0-9]*$");
  //分机号验证
  if ($("#ext").val()) {
    if (!reg.test($("#ext").val())) {
      $("#extErr").html(numtip)
      $("#extErr").show();
    }
    else {
      $("#extErr").hide();
    }
  }
  else {
    $("#extErr").hide();
  }
}

(function ( $, ko) {
  $("#header").load('../compoments/header/header.html',function () {
    $("#headerImg").attr("data-module","个人中心");
    $("#modifypassword").attr("data-module","个人中心");
  });
  $("#footer").load('../compoments/footer/footer.html',function(){
    $('#goSales').attr('href','../personcenter/Sales.html?linksourcemodule=个人中心&backUrl='+encodeURIComponent(location.href))
    $("#footerLogo").attr("src","../public/img/register/foot-logo.png")

  });
  ko.validation.init({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: false,
    parseInputAttributes: true,
    messageTemplate: null
  }, true);
  smarket.ready(function () {
    var ua = new UserAction({
      module: smarket.urlParams.linksourcemodule,// "个人中心",
      title: '注册',
      category1: '注册',
      behaviorType: "浏览网页",
      behaviorResult: "浏览成功"
    });
    ua.notes();
    var RegisterMemberViewModel = smarket.viewModel.RegisterMemberViewModel,
      memberFormId = smarket.urlParams.memberFormId || smarket.Config("rigisterFormId"),
      schemaId = smarket.urlParams.memberSchemaId || smarket.Config("schemaId"),
      backUrl = smarket.urlParams.backUrl,
      configId = smarket.urlParams.configId,
      userInfo = smarket.cookie.smarketMember(schemaId),
      member = smarket.api.member;
    var isVxrailForm = false; // 是否是表单，只显示手机等几个字段
    if (backUrl && backUrl.indexOf('vxrail') !== -1) {
      isVxrailForm = true;
      memberFormId =  smarket.urlParams.memberFormId || smarket.Config("registerVxrailFormId");
    }
    var vm = new RegisterMemberViewModel({
        memberFormId: memberFormId
      });
    var mobilenum;
    vm.email = ko.observable(''); //注册完存cookie
    //特殊字段
    vm.devicetype = ko.observable(smarket.Config('rigisterFields.equipment'));
    vm.platform = ko.observable(smarket.Config('rigisterFields.platform'));
    vm.browser = ko.observable(smarket.Config('rigisterFields.browser'));
    vm.ip = ko.observable(smarket.Config('rigisterFields.IP'));
    vm.linksource = ko.observable(smarket.Config('rigisterFields.link_source'));
    vm.linksourcemodule = ko.observable(smarket.Config('rigisterFields.link_sourcemodule'));
    vm.mediasources = ko.observable(smarket.Config('rigisterFields.mediasources'));
    vm.channelsources = ko.observable(smarket.Config('rigisterFields.channelsources'));
    vm.title = ko.observable(smarket.Config('rigisterFields.title'));
    vm.url = ko.observable(smarket.Config('rigisterFields.url'));
    vm.createtime = ko.observable(smarket.Config('rigisterFields.createTime'));
    vm.padding = ko.observable(false);

    vm.allList = ko.observableArray();
    vm.positionList = smarket.Config("positionList");
    vm.isShow = ko.observable(false);
    vm.beforeRegisterHandler = function (data) {
      data.browseInfo = activeRecord.browseInfo;
      vm.padding(true);
      return true;
    };
    vm.afterRegisterHandler = function (data) {
      //记录用户注册行为
      vm.padding(false);
      $("#checkcodeErr").hide();
      if (data.result == '0') {
        var ua = new UserAction({
          module:  smarket.urlParams.linksourcemodule,//"个人中心",
          category1: '注册',
          title: '注册',
          behaviorType: "注册",
          behaviorResult: "注册成功"
        });
        ua.notes().then(function () {

          if (backUrl) {
            location.href = backUrl;
          } else {
            alert(data.desc);
            $("#maskDiv").hide();
          }
        }, function () {

          if (backUrl) {
            location.href = backUrl;
          } else {
            alert(data.desc);
            $("#maskDiv").hide();
          }
        });

      }
      else if (data.result == '598018')//验证码错误
      {
        vm.checkCode().value.setError(data.desc);
        $("#maskDiv").hide();
        var ua = new UserAction({
          module: smarket.urlParams.linksourcemodule,// "个人中心",
          category1: '注册',
          title: '注册',
          behaviorType: "注册",
          behaviorResult: "注册失败"
        });
        ua.notes();
      }
      else {
        var ua = new UserAction({
          module: smarket.urlParams.linksourcemodule,// "个人中心",
          category1: '注册',
          title: '注册',
          behaviorType: "注册",
          behaviorResult: "注册失败"
        });
        ua.notes();
        $("#maskDiv").hide();
        alert(data.desc);
      }

    };
    //增加处理字段验证
    vm.handler.add(vm, 'cascadeValidator', function (field, validators) {
      if (field.displayType() == '4') {
        validators.validation.push({
          async: false,
          onlyIf: function () {
            return !!field.value();
          },
          validator: function (val, params, callback) {
            if (val.split(',').length >= 1) {
              return val.split(',').length === field.nodes().length;
            }
          },
          message: field.messages.required
        });
      }

    });
    vm.initField = function (field) {
      if (field.fieldType() === 'TEXT') {
        field.messages.required = '请输入' + field.displayName();
      }
      if (field.fieldType() === 'LIST') {
        field.messages.required = '请选择' + field.displayName();
      }
      field.messages.unique = '您输入的' + field.messages.unique;
      if (field.fieldName() === 'password') {
        field.showPassword = ko.observable(false);
      }
      if (field.displayType() == 7 || field.displayType() == 8) {
        field.errorHandler = function (message) {
          alert(message);
        };
      }
      if (field.fieldName() === smarket.Config('rigisterFields.contactAllow') || field.fieldName() === smarket.Config('rigisterFields.privacynotice')) {
        field.messages.required = '请选择';
      }
      if (field.fieldName() === 'province') {
        field.messages.required = '请选择省份或城市'
      }
    };

    //重写发送验证码的接口 添加参数
    (function () {
      var oldFunc = smarket.api.member.sendCheckCode;
      smarket.api.member.sendCheckCode = function (params) {
        params.browseInfo = activeRecord.browseInfo;
        return oldFunc(params);
      };

    })();
    vm.expandField = function (data) {
      console.log(data);
    };
    //过滤部门选项
    vm.filterD = function (arr) {
      vm.fields().forEach(function (f) {
        if (f.fieldName() == 'position') {
          //兼容ie
          f.nodes()[0].options().splice(0,f.nodes()[0].options().length);
          vm.allList().forEach(function (al) {
            arr.forEach(function (i) {
              if (i == al.option()) {
                f.nodes()[0].options.push(al);
              }
            });
          });
          if (f.nodes()[0].selectedOptions().option) {
            f.nodes()[0].selectedOptions([]);
            f.value('');
          }
        }
      })

    };
    vm.fun = function (data) {
      vm.isShow(true);
      switch (data()) {
        case "请选择":
          vm.isShow(false);
          break;
        case "高层管理人员":
          //筛选gc
          vm.filterD(vm.positionList.gc);
          break;
        case "培训":
          vm.filterD(vm.positionList.px);
          break;
        case "销售":
          vm.filterD(vm.positionList.xs);
          break;
        case "采购":
          vm.filterD(vm.positionList.cg);
          break;
        case "运营":
          vm.filterD(vm.positionList.yy);
          break;
        case "市场":
          vm.filterD(vm.positionList.sc);
          break;
        case "IT":
          vm.filterD(vm.positionList.it);
          break;
        case "人力资源":
          vm.filterD(vm.positionList.rl);
          break;
        case "财务":
          vm.filterD(vm.positionList.cw);
          break;
        case "后勤/设备/公共设施":
          vm.filterD(vm.positionList.hq);
          break;
        case "其它":
          vm.filterD(vm.positionList.qt);
          break;
      }
      vm.fields().forEach(function (f) {
        if (f.fieldName() == 'position') {
          f.errors.showAllMessages();
        }
      })
    };

    vm.loadForm().then(function () {
      //接口异步 只能走个定时器来获取数据
      setTimeout(function () {
        vm.fields().forEach(function (f) {
          if (f.fieldName() == 'position') {
            f.nodes()[0].options().forEach(function (item) {
              vm.allList.push(item)
            });
            f.nodes()[0].options().splice(0,f.nodes()[0].options().length);

          }
        })
      }, 2);

      $.each(vm.fields(), function (idx, field) {
        if ($.cookie("smarketMember_isRegister")) {
          //回填手机姓名邮箱公司职位
          if (field.fieldName() == 'mobile' && $.cookie("smarketMember_isRegister").mobile) {
            field.setValue($.cookie("smarketMember_isRegister").mobile.value);
          }
          if (field.fieldName() == 'name' && $.cookie("smarketMember_isRegister").name) {
            field.setValue($.cookie("smarketMember_isRegister").name.value);
          }
          if (field.fieldName() == 'email' && $.cookie("smarketMember_isRegister").email) {
            field.setValue($.cookie("smarketMember_isRegister").email.value);
          }
          if (field.fieldName() == 'enterprise_name' && $.cookie("smarketMember_isRegister").enterprise) {
            field.setValue($.cookie("smarketMember_isRegister").enterprise.value);
          }
          if (field.fieldName() == 'position' && $.cookie("smarketMember_isRegister").position) {
            field.setValue($.cookie("smarketMember_isRegister").position.value);
          }
        }
      });
      ko.applyBindings(vm);
      $("#maskDiv").hide();
      $('.register').show();
      //再次确认密码验证
      $("#passwordAgin").blur(function () {
        if (!$("#passwordAgin").val()) {
          $("#passwordAginErr").show();
          $("#passwordAginErr").text("请再次确认密码");
        }
        else if ($("#password").val() != $("#passwordAgin").val()) {
          $("#passwordAginErr").show();
          $("#passwordAginErr").text("输入的密码不一致");
        }
        else {
          $("#passwordAginErr").hide();
        }
      });
      //点击单选按钮
      var radio = "0";
      $(".rideo-group").find("span").on("click", function () {
        $(this).siblings().removeClass("on");
        $(this).addClass("on");
        radio = $(this).index();
      })
      //点击多选按钮
      var checkbox = true;
      $(".checkbox").find("span").on("click", function () {
        $(this).toggleClass("on");
        checkbox = !checkbox;
      })
      $(document).on("click", ".select-list", function (e) {
        var ev = e || window.event;
        if (ev.stopPropagation) {
          ev.stopPropagation();
        }
        else if (window.event) {
          window.event.cancelBubble = true;//兼容IE
        }
        var _this = $(this).find(".select-tab");
        $(".select-tab").not(_this).removeClass("on").siblings(".select").addClass("demon");
        $(this).find(".select-tab").toggleClass("on").siblings(".select").toggleClass("demon");
      });
      //点击input盒子获取焦点
      $(".input-list").on("click",".input-box,.number",function(){
        $(this).find("input").focus();
        // alert(1);
      })
      $(document).on('click', function () {
        // var e = e || window.event; //浏览器兼容性
        // var elem = e.target || e.srcElement;
        //
        // while (elem) { //循环判断至跟节点，防止点击的是div子元素
        //     if (elem.className && elem.className == 'select') {
        //         return;
        //     }
        //     elem = elem.parentNode;
        // }
        $(".select-tab.on").removeClass("on");
        $(".select").addClass("demon");
      });
    });

    vm.loginUrl = 'login.html?memberFormId=' + memberFormId +
      '&memberSchemaId=' + schemaId +
      (backUrl ? '&backUrl=' + encodeURIComponent(backUrl) : '');

    //记录密码
    if (userInfo && userInfo.session) {
      if (smarket.isUrl(backUrl)) {
        window.location.href = backUrl;
      }
    }
    vm.register = function () {
      $("#maskDiv").show();
      var self = this, fields = self.fields(), isValid = true, answers = [],
        defer = $.Deferred(),
        answer = null, needToken = false,
        submitData = {
          tenantId: self.formInfo.tenantId,
          schemaId: self.formInfo.schemaId,
          memberFormId: self.memberFormId,
          url: window.location.href,
          referenceUrl: (self.inWeChat() ? '微信' : (document.referrer || window.location.href)),
          token: self.token || '',
          verify: self.verify || ''
        };
      if (self.wx && self.wx.weChatId && self.wx.openId) {
        submitData.isBind = true,
          submitData.weChatId = self.wx.weChatId,
          submitData.openId = self.wx.openId;
      }
      //区号验证提示语
      $.each(fields, function (idx, field) {
        //区号和分机号+行为信息字段特殊处理
        if (field.fieldName() == smarket.Config('rigisterFields.ext') || field.fieldName() == smarket.Config('rigisterFields.areacode') || field.fieldName() == smarket.Config('rigisterFields.equipment') || field.fieldName() == smarket.Config('rigisterFields.platform')
          || field.fieldName() == smarket.Config('rigisterFields.browser') || field.fieldName() == smarket.Config('rigisterFields.ip')
          || field.fieldName() == smarket.Config('rigisterFields.link_source') || field.fieldName() == smarket.Config('rigisterFields.link_sourcemodule')
          || field.fieldName() == smarket.Config('rigisterFields.mediasources') || field.fieldName() == smarket.Config('rigisterFields.channelsources')
          || field.fieldName() == smarket.Config('rigisterFields.CreateTime')
        ) {
          return true;
        }
        if (field.errors().length > 0) {
          isValid = false;
          field.errors.showAllMessages();
        } else {
          answer = field.answer();
          if (field.fieldName() === 'password') {
            answer.value = md5(answer.value).toUpperCase();
          }
          if (field.fieldName() === 'email') {
            vm.email(answer.value);
          }
          answers.push(answer);
        }
        if (field.fieldName() === 'mobile' && field.isSendSms == '1') {
          mobilenum = field.answer().value;
          needToken = true;
          if (self.checkCode().errors().length > 0) {
            isValid = false;
            self.checkCode().errors.showAllMessages();
          } else {
            submitData.verificationCode = self.checkCode().value();
          }
        }


      });
      submitData['formData'] = answers;
      //验证字段
      //再次输入密码
      if (!$("#passwordAgin").val()) {
        $("#passwordAginErr").show();
        $("#passwordAginErr").text("请再次输入密码");
        isValid = false;
      }
      if (!isVxrailForm) {
          // 区号验证必填及数字
          var areaCodeVal = $("#areacode").val();
          if (!areaCodeVal || !reg.test(areaCodeVal)) {
              isValid = false;
              $("#areacodeErr").html(!areaCodeVal ? numtip : areacodenulltip).show();
          }
      //分机验证数字
      if (!reg.test($("#ext").val())) {
        isValid = false;
        $("#extErr").html(numtip);
        $("#extErr").show();
      }
        //增加区号和分机号
        submitData['formData'].push({
          'fieldName': smarket.Config('rigisterFields.areacode'),
          'value': $("#areacode").val() ? $("#areacode").val() : ""
        });
        submitData['formData'].push({
          'fieldName': smarket.Config('rigisterFields.ext'),
          'value': $("#ext").val() ? $("#ext").val() : "空"
        });
      }

      //增加字段赋值
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.equipment'),
        'value': activeRecord.browseInfo.equipment
      });
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.platform'),
        'value': activeRecord.browseInfo.os
      });
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.browser'),
        'value': activeRecord.browseInfo.browser
      });
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.IP'),
        'value': smarket.client.ip
      });
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.link_source'),
        'value': document.referrer
      });
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.link_sourcemodule'),
        'value': smarket.urlParams.linksourcemodule || ''
      });
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.mediasources'),
        'value': smarket.urlParams.mediasources || ''
      });
      submitData['formData'].push({
        'fieldName': smarket.Config('rigisterFields.channelsources'),
        'value': smarket.urlParams.channelsource || ''
      });
      /*submitData['formData'].push({
          'fieldName': smarket.Config('rigisterFields.createTime'),
          'value': new Date().format('yyyy-MM-dd HH:mm:ss')
      });*/
      if (isValid && self.beforeRegisterHandler(submitData)) {

        //设置用户信息
        window.userInfo = {
          mobile:'',
          name:'',
          email:'',
          enterprise_name:'',
          position:'',
          province:'',
          industry:'',
          employeesNumber:''
        };
        vm.fields().forEach(function (item) {
          if(item.fieldInfo.fieldName === 'mobile'){
            window.userInfo.mobile = item.value();
          }
          if(item.fieldInfo.fieldName === 'name'){
            window.userInfo.name = item.value();
          }
          if(item.fieldInfo.fieldName === 'email'){
            window.userInfo.email = item.value();
          }
          if(item.fieldInfo.fieldName === 'enterprise_name'){
            window.userInfo.enterprise_name = item.value();
          }
          if(item.fieldInfo.fieldName === 'position'){
            window.userInfo.position = item.value();
          }
          if(item.fieldInfo.fieldName === 'province'){
            window.userInfo.province = item.value();
          }
          if(item.fieldInfo.fieldName === 'industry'){
            window.userInfo.industry = item.value();
          }
          if(item.fieldInfo.fieldName === 'employeesNumber'){
            window.userInfo.employeesNumber = item.value();
          }
        });

        if (needToken) {
          self.getToken().then(function (data) {
            smarket.data('get token', data);
            submitData.token = submitData.token ? [submitData.token, data.content.token] : data.content.token;
            return register(submitData);
          }, function (data) {
            smarket.data('get token error', data);
            return data;
          }).then(function (data) {
            smarket.cookie.smarketMember(self.formInfo.schemaId, {
              session: data.content.sess,
              memberId: data.content.loginId,
              email: vm.email()
            }, {expires: 7});
            self.afterRegisterHandler(data);
            defer.resolve(data);
            gio('track', 'registerSuccess', {'user_Id': data.content.loginId, 'phoneNumber': mobilenum, 'registerEntrance' : '注册入口' })
            gio('track', 'loginSuccess', {'user_Id': data.content.loginId, 'phoneNumber':mobilenum})
            gio('setUserId', data.content.loginId);

            var gioParams = {
              userName_ppl: window.userInfo.name,
              companyName_ppl: window.userInfo.enterprise_name,
              industry_ppl: window.userInfo.industry,
              companyScale_ppl: window.userInfo.employeesNumber,
              userRole_ppl: window.userInfo.position,
              area_ppl: window.userInfo.province,
              email_ppl: window.userInfo.email,
              phone_ppl: window.userInfo.mobile,
            }
            gio('people.set',gioParams);
            //cookie中设置一个用户手机
            $.cookie('Activity_MOBILE', 'MOBILE'+window.userInfo.mobile+'number', { expires: 365, path: '/', domain: smarket.Config('cookie.domain')||window.location.host });
            try {
              window.oct.on_register(data.content.loginId);
            } catch (error) {
              console.log(error)
            }

          }, function (data) {
            self.afterRegisterHandler(data);
            defer.reject(data);
          });
        } else {
          register(submitData).then(function (data) {
            smarket.cookie.smarketMember(self.formInfo.schemaId, {
              session: data.content.sess,
              memberId: data.content.loginId,
              email: vm.email()
            }, {expires: 7});
            self.afterRegisterHandler(data);
            defer.resolve(data);
             gio('track', 'registerSuccess', {'user_Id': data.content.loginId, 'phoneNumber': mobilenum, 'registerEntrance' : '注册入口' })
             gio('track', 'loginSuccess', {'user_Id': data.content.loginId, 'phoneNumber':mobilenum})
             gio('setUserId', data.content.loginId);
            var gioParams = {
              userName_ppl: window.userInfo.name,
              companyName_ppl: window.userInfo.enterprise_name,
              industry_ppl: window.userInfo.industry,
              companyScale_ppl: window.userInfo.employeesNumber,
              userRole_ppl: window.userInfo.position,
              area_ppl: window.userInfo.province,
              email_ppl: window.userInfo.email,
              phone_ppl: window.userInfo.mobile,
            }
            gio('people.set',gioParams);
            //cookie中设置一个用户手机
            $.cookie('Activity_MOBILE', 'MOBILE'+window.userInfo.mobile+'number', { expires: 365, path: '/', domain: smarket.Config('cookie.domain')||window.location.host });
            try {
              window.oct.on_register(data.content.loginId);
            } catch (error) {
              console.log(error)
            }
          }, function (data) {
            self.afterRegisterHandler(data);
            defer.reject(data);
          });
        }

      } else {
        $("#maskDiv").hide();
        smarket.data('valid fail', submitData);
        defer.reject({
          result: 1,
          desc: isValid ? '取消发送' : '验证错误'
        });
        if (!isValid) {
          self.validationErrorHandler();
        }
      }

      function register(submitData) {
        smarket.data('submit form', submitData);
        return member.register(submitData).then(function (data) {
          smarket.data('response', data);
          return data;
        }, function (data) {
          smarket.data('response error', data);
          return data;
        });
      }
      setTimeout(function() {
        for(var i = 0;i<$(".error-hint").length;i++){
          var errstyle = $(".error-hint").eq(i).attr("style");
          if(errstyle == "" || errstyle == undefined){
            console.log(i);
            var errtop = $(".error-hint").eq(i).offset().top;
            $("html,body").animate({scrollTop:errtop - 300},300,"easeInOutCubic");
            break;
          }
        }
      }, 10);
      return defer.promise();

    };
    // gdt('track', 'REGISTER'); // 注册
  });
})(jQuery);
